package com.azhon.appupdate.dialog;

import com.azhon.appupdate.ResourceTable;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.azhon.appupdate.utils.ApkUtil;
import com.azhon.appupdate.utils.Constant;
import com.azhon.appupdate.utils.ScreenUtil;
import com.azhon.appupdate.utils.TextUtil;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.app.Context;
import ohos.multimodalinput.event.KeyEvent;

import java.io.File;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

/**
 * 项目名:    AppUpdate
 * 包名       com.azhon.appupdate.dialog
 * 文件名:    UpdateDialog
 * 创建时间:  2018/1/30 on 15:13
 * 描述:     TODO 显示升级对话框
 *
 * @author 阿钟
 */

public class UpdateDialog extends CommonDialog implements Component.ClickedListener, OnDownloadListener {
    private Context context;
    private DownloadManager manager;
    private boolean forcedUpgrade;
    private Button update;
    private ProgressBar progressBar;
    private int dialogImage, dialogButtonTextColor, dialogButtonColor, dialogProgressBarColor;
    private OnButtonClickListener buttonClickListener;
    private File apk;
    private final int install = 0x45F;
    private DirectionalLayout layoutImage;
    private static final int MAX = 100;
    private static final float RADIUS = 20f;

    public UpdateDialog(Context context) {
        super(context);
        layoutImage = (DirectionalLayout) LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_update, null, false);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        manager = DownloadManager.getInstance();
        UpdateConfiguration configuration = manager.getConfiguration();
        configuration.setOnDownloadListener(this);
        forcedUpgrade = configuration.isForcedUpgrade();
        buttonClickListener = configuration.getOnButtonClickListener();
        dialogImage = configuration.getDialogImage();
        dialogButtonTextColor = configuration.getDialogButtonTextColor();
        dialogButtonColor = configuration.getDialogButtonColor();
        dialogProgressBarColor = configuration.getDialogProgressBarColor();
        setWindowSize(context);
        setTransparent(true);
        initView();
    }

    private void initView() {
        Text title = (Text) layoutImage.findComponentById(ResourceTable.Id_tv_title);
        Text size = (Text) layoutImage.findComponentById(ResourceTable.Id_tv_size);
        Image ivBg = (Image) layoutImage.findComponentById(ResourceTable.Id_iv_bg);
        Image ibClose = (Image) layoutImage.findComponentById(ResourceTable.Id_ib_close);
        Text description = (Text) layoutImage.findComponentById(ResourceTable.Id_tv_description);
        DirectionalLayout box = (DirectionalLayout) layoutImage.findComponentById(ResourceTable.Id_box);
        DirectionalLayout line = (DirectionalLayout) layoutImage.findComponentById(ResourceTable.Id_line);
        progressBar = (ProgressBar) layoutImage.findComponentById(ResourceTable.Id_np_bar);
        progressBar.setVisibility(forcedUpgrade ? Component.VISIBLE : Component.HIDE);
        update = (Button) layoutImage.findComponentById(ResourceTable.Id_tv_btn_update);
        update.setTag(0);
        update.setClickedListener(this);
        ibClose.setClickedListener(this);
        //自定义
        if (dialogImage != -1) {
            ivBg.setPixelMap(dialogImage);
        }
        if (dialogButtonTextColor != -1) {
            update.setTextColor(new Color(dialogButtonTextColor));
        }
        if (dialogButtonColor != -1) {
            ShapeElement drawable = new ShapeElement(context, ResourceTable.Graphic_bg_button);
            drawable.setRgbColor(RgbColor.fromArgbInt(dialogButtonColor));
            update.setBackground(drawable);
        }
        if (dialogProgressBarColor != -1) {
            progressBar.setProgressColor(new Color(dialogProgressBarColor));
            progressBar.setProgressHintTextColor(new Color(dialogProgressBarColor));
        }
        //强制升级
        if (forcedUpgrade) {
            line.setVisibility(Component.HIDE);
            ibClose.setVisibility(Component.HIDE);
            siteKeyboardCallback(new KeyboardCallback() {
                @Override
                public boolean clickKey(IDialog dialog, KeyEvent event) {
                    //屏蔽返回键
                    return event.getKeyCode() == KeyEvent.KEY_BACK;
                }
            });
        }
        //设置界面数据
        if (!TextUtil.isEmpty(manager.getApkVersionName())) {
            String newVersion = context.getString(ResourceTable.String_dialog_new);
            title.setText(String.format(newVersion, manager.getApkVersionName()));
        }
        if (!TextUtil.isEmpty(manager.getApkSize())) {
            String newVersionSize = context.getString(ResourceTable.String_dialog_new_size);
            size.setText(String.format(newVersionSize, manager.getApkSize()));
            size.setVisibility(Component.VISIBLE);
        }
        description.setText(manager.getApkDescription());
        ShapeElement element = new ShapeElement(context, ResourceTable.Graphic_background_ability_main);
        element.setCornerRadiiArray(new float[]{
                0f, 0f,
                0f, 0f,
                RADIUS, RADIUS,
                RADIUS, RADIUS
        });
        box.setBackground(element);
    }

    private void setWindowSize(Context context) {
        setContentCustomComponent(layoutImage);
        int width = (int) (ScreenUtil.getWidth(context) * 0.7f);
        setSize(width, MATCH_CONTENT);
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        if (id == ResourceTable.Id_ib_close) {
            if (!forcedUpgrade) {
                destroy();
            }
            //回调点击事件
            if (buttonClickListener != null) {
                buttonClickListener.onButtonClick(OnButtonClickListener.CANCEL);
            }
            manager.release();
        }
        if (id == ResourceTable.Id_tv_btn_update) {
            if ((int) update.getTag() == install) {
                installApk();
                return;
            }
            if (forcedUpgrade) {
                update.setEnabled(false);
                update.setText(ResourceTable.String_background_downloading);
            } else {
                destroy();
            }
            //回调点击事件
            if (buttonClickListener != null) {
                buttonClickListener.onButtonClick(OnButtonClickListener.UPDATE);
            }
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.azhon.appupdate_ohos")
                    .withAbilityName("com.azhon.appupdate.service.DownloadService")
                    .build();
            intent.setOperation(operation);
            context.startAbility(intent, 1);
            manager.setCanStart(false);
        }
    }

    /**
     * 强制更新，点击进行安装
     */
    private void installApk() {
        ApkUtil.installApk(context, Constant.AUTHORITIES, apk);
    }

    @Override
    public void start() {

    }

    @Override
    public void downloading(int progress) {
        if (progressBar.getVisibility() == Component.VISIBLE) {
            progressBar.setProgressValue(progress);
            progressBar.setProgressHintText(progress + "%");
        } else {
            progressBar.setVisibility(Component.HIDE);
        }
    }

    @Override
    public void done(File apk) {
        this.apk = apk;
        if (forcedUpgrade) {
            progressBar.setProgressValue(MAX);
            progressBar.setProgressHintText(MAX + "%");
            update.setTag(install);
            update.setEnabled(true);
            update.setText(ResourceTable.String_click_hint);
        }
    }

    @Override
    public void cancel() {

    }

    @Override
    public void error(Exception e) {

    }
}
